const exec = require('child_process').exec,
    path = process.cwd(),
    fs = require('fs');
let prog = null,
    args = null;

function install() {

}

function removeTarget(path){
    let targetName = argv[1];
}

function parsePath(targetPath,rebuild){
    //只处理-dev结尾的目录,找到目标,用fis3 remove
    let hasComponents = false,
        hasComponentJson = false;

    fs.readdir(targetPath, (err, files) => {
        if (err) {
            console.log('read dir error');
        } else {
            console.log(files)
            // files.forEach((item) => {
            //     let tmpPath = targetPath + '/' + item;
            //     if(item === 'components'){
            //         let stat = fs.lstatSync(tmpPath);
            //         hasComponents = true;
            //     }else if(item === 'component.json'){
            //         hasComponentJson = true;
            //     }

            // });
            // if(hasComponentJson && hasComponents){
            //     removeTarget(targetPath + '/' + components);
            // }
        }
    });
}

function remove(rebuild) {
    //从当前文件夹开始遍历所有目录
    parsePath(path,rebuild);
}

function serverStart(){
    if(prog.root && typeof prog.root !=='string'){
        console.error('input the root');
        return;
    }
    let path = process.cwd().replace(/\\/g, '/');
    path = prog.root||`${path}/output`;
    let cmd = `fis3 server start --root ${path}`;
    console.log(cmd);
    const result = exec(cmd, (err, stdout, stderr) => {
        if (err) {
            console.error(err);
        }
    });
    result.stderr.pipe(process.stderr); 
    result.stdout.pipe(process.stdout); 
    result.on('exit', (code, signal) => {

    });
}

function execStr(cmd){
    if(prog.args){
        prog.args.forEach((it)=>{
            cmd+= ` ${it}`;
        });
    }
    console.log(cmd);
    const result = exec(cmd, (err, stdout, stderr) => {
        if (err) {
            console.error(err);
        }
    });
    result.stderr.pipe(process.stderr); 
    result.stdout.pipe(process.stdout); 
    result.on('exit', (code, signal) => {

    });
}

function serverStop(){
    let cmd = `fis3 server stop`;
    console.log(cmd);
    const result = exec(cmd, (err, stdout, stderr) => {
        if (err) {
            console.error(err);
        }
    });
    result.stderr.pipe(process.stderr); 
    result.stdout.pipe(process.stdout); 
    result.on('exit', (code, signal) => {

    });
}

module.exports = function() {
    prog = arguments[0];
    args = prog.args;
    if (prog.start) {
        serverStart();
    }else if (prog.stop) {
        serverStop();
    }else if (prog.r||prog.release) {
        execStr('fis3 release');
    }else if (prog.i||prog.install) {
        execStr('fis3 install');
    }
}

